/*
 * Copyright 2014 by État de Genève (Switzerland)
 * All rights reserved.
 *
 * Author: ELCA Informatique SA
 */
define(['moment', 
        'services/formatter', 
        'bindings/validation'], 
    function (moment, formatter, validations) {

    return {
        init: function (element, valueAccessor, allBindingsAccessor) {
            // validations[bindingContext.format].init(element, valueAccessor, allBindingsAccessor);
            if (valueAccessor() !== null && typeof valueAccessor() === 'object' && valueAccessor().format) {
                validations[valueAccessor().format].init(element, valueAccessor, allBindingsAccessor);
            }
        },
        update: function (element, valueAccessor, allBindingsAccessor) {
            if (typeof valueAccessor() !== 'object' || valueAccessor() === null || (typeof valueAccessor() === 'object' && valueAccessor())) {
                var value = ko.unwrap(valueAccessor());

                // format property is the name of the formatter function we want to use
                var format = allBindingsAccessor().format || '_default';

                // format can be an object. In this case, the name of the formatter function is the 'function' property of that object
                // the rest of the object is considered 'additional parameters' for the formatting function, and is passed 'as is' to the formatter
                var formatterFunc = null;
                var additionalParams = undefined;
                if (typeof format === 'object') {
                    formatterFunc = format.function;
                    additionalParams = format;
                } else {
                    formatterFunc = format;
                }

                // find the formatting function in the formatter
                var formatFunc = formatter[formatterFunc] || formatter['_default'];

                // call the function, pass in potential additional params (if format was an object), and put the result in the HTML
                $(element).html(formatFunc(value, additionalParams));
            } else {
                if (valueAccessor() !== null && valueAccessor().format) {
                    validations[valueAccessor().format].update(element, valueAccessor, allBindingsAccessor);
                }
            }
        }
    };
});